import { spawn } from 'child_process'

export function getApps(): Promise<AppInfo[]> {
  return new Promise((resolve, reject) => {
    let resultBuffer = Buffer.from([])

    const profileInstalledApps = spawn('/usr/sbin/system_profiler', [
      '-json',
      '-detailLevel',
      'mini',
      'SPApplicationsDataType'
    ])

    profileInstalledApps.stdout.on('data', (chunckBuffer: Buffer) => {
      resultBuffer = Buffer.concat([resultBuffer, chunckBuffer])
    })

    profileInstalledApps.on('exit', (exitCode: number) => {
      if (exitCode !== 0) {
        return reject(new Error(`system_profiler exited with code ${exitCode}`))
      }

      try {
        const installedApps = JSON.parse(resultBuffer.toString())

        installedApps.SPApplicationsDataType = installedApps.SPApplicationsDataType.filter(
          (app) =>
            typeof app.path === 'string' &&
            (app.path.includes('/Applications') || app.path.includes('Finder.app'))
        )

        return resolve(
          installedApps.SPApplicationsDataType.map((app) => ({
            path: app.path,
            name: typeof app._name === 'string' ? app._name : 'unknown'
          })) as AppInfo[]
        )
      } catch (err) {
        reject(err)
      }
    })

    profileInstalledApps.on('error', reject)
  })
}
